package com.hmdp.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hmdp.common.Constants;
import com.hmdp.common.HostHolder;
import com.hmdp.common.R;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IUserInfoService;
import com.hmdp.service.IUserService;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 公众号：是叶十三
 * @since 2021-12-22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController implements Constants {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @Resource
    private IBlogService blogService;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public R sendCode(@RequestParam("phone") String phone, HttpSession session) {
        return userService.sendCode(phone, session);
    }

    /**
     * 登录功能
     *
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        return userService.login(loginForm, session);
    }

    /**
     * 登出功能
     *
     * @return 无
     */
    @PostMapping("/logout")
    public R logout() {
        // TODO 实现登出功能
        return R.fail("功能未完成");
    }

    /**
     * 获取当前登录的用户并返回
     *
     * @return
     */
    @GetMapping("/me")
    public R me() {
        UserDTO user = HostHolder.getUser();
        return R.ok(user);
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long userId) {
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return R.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return R.ok(info);
    }

    @GetMapping("/{id}")
    public R queryUserById(@PathVariable("id") Long userId) {
        // 查询详情
        User user = userService.getById(userId);
        if (ObjectUtils.isEmpty(user)) {
            return R.ok();
        }
        // 属性拷贝
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return R.ok(userDTO);
    }

}
